import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text ,Button,Video } from '@tarojs/components'
import '../../assets/common.scss'
import '../../assets/animate.min.scss'
import CommonJs from '../../utils/common'
import './zhibo.scss'




export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      result: [],
      showgg:0,
      shareindex:0,
      pmwidth:0,
      ispyqfx:0,
      ewm:''
    }
  }
  config = {
    navigationBarTitleText:'热门直播',
    usingComponents: {
      "subscribe": "plugin-private://wx2b03c6e691cd7370/components/subscribe/subscribe"
    }
  }

  componentWillMount () {
  	var roomid = this.$router.params.scene
    if(roomid){
  		var url='/plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id='+roomid;
		  CommonJs.openTo(url);
  	}
    this.getdate()
    var _this=this;
  	Taro.getSystemInfo({
		  success: res => 
		  _this.setState({
        pmwidth: res.screenWidth
      })
		})
  }
  componentDidShow () {
  	
  }
  componentDidUpdate () {
  }
  starlive(roomid,type){
  	
  	if(type==101){
	  	var url='/plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id='+roomid;
		  CommonJs.openTo(url);
		}
  	else if(type==102){
  		Taro.showToast({
        title:'主播还未开始直播，可以先订阅关注',
        icon: 'none',
        duration: 1000
      })
  	}
  	else{
  		 CommonJs.openTo('/pages/zhibo/history?scene='+roomid);
  	}
  }
  getdate(){
	  var webinfo=Taro.getStorageSync('webinfo')
		if(webinfo){
		   var shopId=Taro.getStorageSync('shopId')
			var url='/live/papi/v1.9/rooms/getliveinfo?shopId.equals='+ shopId +'&page=0&size=1000'
		}
	    else{
		var url='/live/papi/v1.9/rooms/getliveinfo?page=0&size=1000'
	  }
  	
  	var _this=this;
  	CommonJs.ajaxRequest(url,'','GET',function(res){
  		if(res.data){
		 		_this.setState({
		      result:res.data
		    })
		 	}
  	})
  }
  getstate(type){
  	if(type==101){
  		return 'zhibo-state zhibo-state01'
  	}
  	else if(type==102){
  		return 'zhibo-state'
  	}
  	else if(type==103){
  		return 'zhibo-state zhibo-state02'
  	}
  	else{
  		return ''
  	}
  }  
  getstatename(type){
  	if(type==101){
  		return '直播中'
  	}
  	else if(type==102){
  		return '即将开始'
  	}
  	else if(type==103){
  		return '历史回顾'
  	}
  	else{
  		return ''
  	}
  }  
  share(index){
  	this.setState({
	      shareindex:index
	  })
  	this.getShareEwm(index);
  }
  sharecancle(){
  	this.setState({
	      showgg:0,
	      shareindex:0
	  })
  }
  onShareAppMessage(res){
  	var index=this.state.shareindex;
  	var ret=this.state.result;
  	var red=ret[index];
    let title ='听说看我直播的都发财了，男生越来越帅，女生，越来越漂亮了！'
		let path = '/pages/zhibo/index?scene='+red.roomid
		var logo=ret.cover_img;
		return CommonJs.onShareAppMessage(title, path, logo)
		this.setState({
	      showgg:0,
	      shareindex:0
	  })
  }
  pyqshare(){
  	Taro.showToast({
	    title:'正在加载数据...',
	    icon: 'none',
	    duration:1000
	  });
  	var index=this.state.shareindex;
  	var ret=this.state.result;
  	var red=ret[index];
  	let ctx = Taro.createCanvasContext('cardCanvas')
    
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, 0, 600, 5000);
    
    
    ctx.setFontSize(16)
    ctx.setFillStyle('black')
    var _this=this;
    var ewmsrc=this.state.ewm
    if(!ewmsrc){
    	Taro.showToast({
	      title:"小程序二维码获取错误，请重试",
	      icon: 'none',
	      duration: 2000
	    })
    	return false;
    }
		var logo=red.localShareImg;
	  if(!logo){
	    logo=CommonJs.geturl()+'/kedouimg01/zhibao.png'
    }
	  console.log(logo)
	  var n=parseInt(this.state.pmwidth)*0.8;
    Taro.getImageInfo({
        src:logo,
	      success: function (ret) {
	      	ctx.drawImage(ret.path, 0, 0,n, ret.height*(n/ret.width))
	      	var h=ret.height*(n/ret.width);
	      	var tit=red.name;
			    var tith=0;
			    if(tit.length>17){
			    	ctx.fillText(tit.substring(0,17),20,30+h);
			    	ctx.fillText(tit.substring(17,tit.length),20,50+h)
			    	tith=60+h
			    }
			    else{
			    	ctx.fillText(tit,20,30+h);
			    	tith=40+h
			    }
			    
			    ctx.setFontSize(14)
			    ctx.setFillStyle('#999')
			    var time="直播时间："+CommonJs.FormatDate(red.start_time*1000,2)+"至"+CommonJs.FormatDate(red.end_time*1000,2)
			    ctx.fillText(time,20,tith+20)
			    tith=tith+20+20
			    
			    ctx.setFontSize(14)
			    ctx.setFillStyle('#333')
			    var address='听说看我直播的都发财了，男生越来越帅，女生，越来越漂亮了!主播带你上高速';
			    var addressarr=[];
			    if(address.length>18){
			    	addressarr.push(address.substring(0,18))
			    	addressarr.push(address.substring(18,address.length))
			    	
			    }
			    else{
			    	addressarr.push(address)
			    }
			    for(var i=0;i<addressarr.length;i++){
			    	ctx.fillText(addressarr[i],20,tith+(i+1)*20)
			    }
			    tith=tith+addressarr.length*20
			    ctx.setFontSize(14)
			    ctx.setFillStyle('#999')
			    var ptext="长按扫码优惠多多";
			    ctx.fillText(ptext,20,tith+80)
	      	Taro.getImageInfo({
		        src:ewmsrc,
			      success: function (res) {
			      	ctx.drawImage(res.path, 170, tith+20, 100, 100)
			      	ctx.restore()
							ctx.draw()
							_this.setState({
							  showgg:0,
							  ispyqfx:1
					    })
			      }
					})
	      }
		})
    
    
  }
  closeshare(){
  	this.setState({
		  ispyqfx:0
    })
  }
  saveimg(){
  	
  	let res = Taro.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 600,
      height:1000,
      canvasId: 'cardCanvas',
      fileType: 'png',
      success:function(ret){
      	console.log(ret.tempFilePath)
      	Taro.saveImageToPhotosAlbum({
		      filePath: ret.tempFilePath,
		      success:function(red){
		      	Taro.showModal({
			        title: '图片保存成功',
			        content: '图片成功保存到相册了，快去发朋友圈吧~',
			        showCancel: false,
			        confirmText: '确认'
			      })
		      },
		      fail:function(){
		      	Taro.showModal({
			        title: '图片保存失败',
			        content: '请重新尝试!',
			        showCancel: false,
			        confirmText: '确认'
			      })
		      }
		    })
      },
      fail:function(){
      	Taro.showModal({
	        title: '图片保存失败',
	        content: '请重新尝试!',
	        showCancel: false,
	        confirmText: '确认'
	      })
      }
   })
  }
  getShareEwm(index){
  	/*获取分享的二维码*/
  	var _this=this;
  	var ret=this.state.result;
  	var red=ret[index];
  	var url="/clusterlog/getWxSmallQrCode?page=pages/zhibo/index&scene="+red.roomid;

	  CommonJs.ajaxRequest(url,'','GET',function(res){
		var ewmsrc=res.content;
	     if(res.code!=300) {
	     	  ewmsrc=ewmsrc.replace(/http:\/\/storage/, "https://xjzbsmall")
	      	_this.setState({
		        ewm:ewmsrc,
		        showgg:1,
		      })
	      	
	     }  
	      else {
	        Taro.showToast({
	          title:res.msg,
	          icon: 'none',
	          duration: 2000
	        })
	      }
	  })
  }
  render () {
    const livelist=this.state.result;
    return (
    	<View className='page zhibopage'>
       	<View className='zhibo-list' style={livelist.length>0?'':'display:none;'}>
       		{livelist&&livelist.map((item, index) => (
       		<View className='zhibo-dl' style={item.live_status>103?'display:none':''}>
       			<View className='zhibo-dt'>
       				<Image className='qun-userg' mode='widthFix' src={item.cover_img} onClick={this.starlive.bind(this,item.roomid,item.live_status)}></Image>
       				<View className={this.getstate(item.live_status)}>{this.getstatename(item.live_status)}</View>
       				<View className='zhibo-state zhibo-dy' style={item.live_status!=102?'display:none':''}><subscribe room-id={item.roomid}>订阅关注</subscribe></View>
       				<View className='zhibo-state zhibo-share' style={item.live_status!=102?'display:none':''} onClick={this.share.bind(this,index)}>邀请好友一起</View>
       				
       			</View>
       			<View className='zhibo-dd' onClick={this.starlive.bind(this,item.roomid,item.live_status)}>
       				<View className='zhibo-tit'>{item.name}</View>
       				<View className='zhibo-info'>
       					<Text className='zhibo-zhubao'>{item.anchor_name}</Text>
       					{CommonJs.FormatDate(item.start_time*1000,3)}
       				</View>
       			</View>
       		</View>
       		 ))}
					
       	</View>
       	<View className='zhibo-list' style={livelist.length>0?'display:none;':'padding:0;'}>
       			<View className='nodate'>暂无直播间数据</View>
       	</View>
       	<View className={this.state.showgg==1?'sharebg':'sharebg sharebgnone'}></View>
       	<View className={this.state.showgg==1?'sharebox animated bounceInUp':'sharebox hiddgg'}>
						<Button openType='share' className='share-li'>分享给朋友</Button>
						<View className='share-li' onClick={this.pyqshare.bind(this)}>分享到朋友圈</View>
						<View className='share-li share-cancle' onClick={this.sharecancle.bind(this)}>取消</View>
				</View>
				<View className='pyqshare' style={this.state.ispyqfx==1?'':'display:none;'}>
		       <Canvas className="card-canvas" canvasId="cardCanvas" ></Canvas>
		       <View className='share-btn'>
		       		<Text className='btn01' onClick={this.saveimg}>保存到相册后分享</Text>
              <Text className='btn02' onClick={this.closeshare}>关闭</Text>
		       </View>
	      </View>
      </View>
    )
  }
}
